import { OneModal } from '@/components/one-ui';
import { UserManageContext, UserOtherHandleContext } from '../hooks';
import { IUseAddOrEditModal, IUserFormRef } from '../type';
import { Ref, useCallback, useContext, useEffect, useRef, useState } from 'react';
import { IOneModalRef } from '@/pages/type';
import { Button, message, Spin, Steps } from 'antd';
import { UserAddOrEditForm } from './UserAddOrEditForm';
import { getUserRowByID } from '../hooks/userManageTableServices';
import { UserAddOrEditPos } from './UserAddOrEditPos';
import { useRequest } from 'umi';
import { getCompanyID, getPosIDs, getUserDepID, getUserID, requestFunCompon } from '@/utils';

export const UseAddOrEditModal: React.FC<IUseAddOrEditModal> = ({
  onClose, //关闭弹框
  checkRows, //是否显示modal
}) => {
  const steps = [
    {
      title: '基本信息',
    },
    {
      title: '设置岗位',
    },
  ];

  const userAddEditRef: Ref<IOneModalRef> = useRef(null); //弹框的ref
  const userAddRef = useRef<IUserFormRef>(null); //第一步的 ref

  const { userFixCls, rightRoladTabieUser } = useContext(UserManageContext);
  const { currentStep, userOthDispatch, twoLeftSelectKeys } = useContext(UserOtherHandleContext);
  const { userDetail, userInfoLoading } = getUserRowByID(checkRows); //获取数据详情
  // const { areadList } = getAreadData({}, curRes);  //获取行政区域

  // 第一步输入的数据
  const [formFirstStep, setFormFirstStep] = useState<any>();
  const saveFormValues = useCallback(
    (record: any) => {
      setFormFirstStep(record);
    },
    [formFirstStep],
  );

  useEffect(() => {
    if (userDetail && userDetail?.id) {
      handEditPOSData(userDetail);
    }
    return () => {
      userOthDispatch({
        type: 'remove-allOtherHandle-state',
      });
    };
  }, [userDetail]);

  // 处理编辑选择的岗位数据
  const handEditPOSData = (resObj: any) => {
    let posIds: any[] = [];
    let posRows: any[] = [];
    if (resObj?.id && resObj?.mpositionList?.length > 0) {
      resObj?.mpositionList?.forEach((item: any) => {
        posIds?.push(item?.id);
        posRows?.push({ ...item, textType: item?.postType });
      });
      userOthDispatch({
        type: 'otherHandle-twoLeftSelectKeys',
        payload: posIds,
      });
      userOthDispatch({
        type: 'otherHandle-twoLeftSelectRows',
        payload: posRows,
      });
    } else {
      userOthDispatch({
        type: 'otherHandle-twoLeftSelectKeys',
        payload: [],
      });
      userOthDispatch({
        type: 'otherHandle-twoLeftSelectRows',
        payload: [],
      });
    }
  };

  /* 关闭弹窗 */
  const onCloseModal = () => {
    if (userAddEditRef) {
      if (userAddEditRef.current) {
        if (userAddEditRef.current.onModalCancel) {
          userAddEditRef.current.onModalCancel();
        }
      }
    }
  };

  // 点击上一步下一步 stepType = true  为下一步  false 为下一步
  const onCurrentStep = (stepType: boolean) => {
    let stepIndex = currentStep;
    if (stepType) {
      userAddRef?.current?.userAddEditForm?.validateFields()?.then((values: any) => {
        stepIndex = stepIndex + 1;
        saveFormValues(values);
        userOthDispatch({
          type: 'otherHandle-currentStep',
          payload: stepIndex,
        });
      });
    } else {
      stepIndex = stepIndex - 1;
      userOthDispatch({
        type: 'otherHandle-currentStep',
        payload: stepIndex,
      });
    }
  };

  // 处理用户设置岗位后 返回的所属部门 和所属公司参数

  // 用户保存新增编辑的方法
  const saveUserDataFunc = () => {
    if (userDetail && userDetail?.id) {
      userAddRef?.current?.userAddEditForm?.validateFields()?.then((values: any) => {
        let paramsObjEdit = {
          ...values,
          // provinceCode: formFirstStep?.node?.[0] ?? userDetail?.provinceCode,
          // cityCode: formFirstStep?.node?.[1] ?? userDetail?.cityCode,
          // countyCode: formFirstStep?.node?.[2] ?? userDetail?.countyCode,
          id: userDetail?.id,
          versionNum: userDetail?.versionNum,
          modifyerID: getUserID(),
          modifyPositionID: getPosIDs(),
          modifyDepartmentID: getUserDepID(),
          modifyCompanyID: getCompanyID(),
          isOpen: 1,
          isAgent: 0, // 默认传参 坐席为0
        };
        addOrEditModal?.run(paramsObjEdit, 'editUser');
      });
    } else {
      let paramsObjAdd = {
        ...formFirstStep,
        isOpen: 1,
        // provinceCode: formFirstStep?.node?.[0] ?? null,
        // cityCode: formFirstStep?.node?.[1] ?? null,
        // countyCode: formFirstStep?.node?.[2] ?? null,
        userPositionID: twoLeftSelectKeys?.length > 0 ? twoLeftSelectKeys?.toString() : null,
        createrID: getUserID(),
        createPositionID: getPosIDs(),
        createDepartmentID: getUserDepID(),
        createCompanyID: getCompanyID(),
        isAgent: 0, // 默认传参 坐席为0
      };
      // delete paramsObjAdd['node']
      if (twoLeftSelectKeys?.length > 0) {
        addOrEditModal?.run(paramsObjAdd, 'addUser');
      } else {
        message.warning('请选择至少一个岗位！', 4);
      }
    }
  };

  // 新增或者编辑方法
  const addOrEditModal = useRequest(
    (paramsObj: any, serType: string) => {
      let bodyParams = {
        ...paramsObj,
      };
      let reqUrl = serType == 'addUser' ? '/userController/add' : serType == 'editUser' ? '/userController/edit' : '';
      let methodType = serType == 'addUser' ? 'POST' : serType == 'editUser' ? 'PUT' : '';
      return requestFunCompon(methodType, reqUrl, bodyParams);
    },
    {
      manual: true,
      onSuccess(data: any): void {
        if (data && data?.msgFlag) {
          message?.success(data?.msg);
          onCloseModal();
          rightRoladTabieUser();
        } else {
          message?.error(data?.msg);
        }
      },
    },
  );

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={userAddEditRef}
        title={checkRows && checkRows?.id ? '编辑用户信息' : '添加用户信息'}
        width={document.body.clientWidth * 0.5}
        onCancel={onClose}
        className={userFixCls + 'addEditModalStyle'}
        footer={
          <>
            {checkRows && checkRows?.id ? (
              <></>
            ) : (
              <>
                {currentStep != 0 && (
                  <Button
                    type={'primary'}
                    onMouseOut={(event: any) => {
                      event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                    }}
                    onClick={() => {
                      onCurrentStep(false);
                    }}
                  >
                    上一步
                  </Button>
                )}
                {currentStep != 1 && (
                  <Button
                    type={'primary'}
                    onMouseOut={(event: any) => {
                      event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
                    }}
                    onClick={() => {
                      onCurrentStep(true);
                    }}
                  >
                    下一步
                  </Button>
                )}
              </>
            )}
            <Button onClick={onCloseModal}>取消</Button>
            <Button
              type={'primary'}
              onMouseOut={(event: any) => {
                event?.target?.nodeName == 'BUTTON' ? event?.target?.blur() : event.target.parentNode.blur();
              }}
              onClick={saveUserDataFunc}
              disabled={userDetail && userDetail?.id ? false : currentStep == 1 ? false : true}
              loading={addOrEditModal?.loading}
            >
              保存
            </Button>
          </>
        }
        bodyStyle={{
          padding: '5px 0px',
          // height: window.screen.height * 0.5,
        }}
        centered
      >
        <div className={userFixCls + 'modalChildren'}>
          <Spin spinning={userInfoLoading || addOrEditModal?.loading}>
            {checkRows && checkRows?.id ? (
              <></>
            ) : (
              <div className={userFixCls + 'modalChildren-stepCurrent'}>
                <Steps size="small" current={currentStep} items={steps} />
              </div>
            )}
            {currentStep == 0 && (
              <UserAddOrEditForm
                ref={userAddRef}
                detailInfoObj={userDetail}
                formValues={formFirstStep}
                // areadList={areadList}
                areadList={[]}
              />
            )}

            {currentStep == 1 && <UserAddOrEditPos />}
          </Spin>
        </div>
      </OneModal>
    </>
  );
};
